package cn.ipanel.bigdata.boot.date

/**
 * Author: lzz
 * Date: 2021/11/22 19:11
 */
case class Month(st: Long, et: Long, len: Int) extends Date(st, et) {

  override def prev(n: Int = 1): Month = {
    var m: Month = this
    for (_ <- 1 to n)
      m = Month(m.st - Date.DAY_TIME)
    m
  }

  override def next(n: Int = 1): Month = {
    var m: Month = this
    for (_ <- 1 to n)
      m = Month(m.et + Date.DAY_TIME + 1)
    m
  }

  lazy final val minDayMonth: Int = 0
  lazy final val maxDayMonth: Int = len - 1
  lazy final val lenDayMonth: Int = maxDayMonth + 1

  def getDay(n: Int): Day = {
    if (n < minDayMonth) null
    else if (n > maxDayMonth) null
    else Day(st + Date.DAY_TIME * n)
  }

  def toYearIndex: Int = toMonth

  override def toString: String = s"Month(${STime.toYYYYMMddHHmmss} To ${ETime.toYYYYMMddHHmmss})"
}

object Month {

  def unapply(yyyyMMdd: String): Option[(Long, Long, Int)] = {
    unapply(Time(yyyyMMdd).time)
  }

  def unapply(time: Long): Option[(Long, Long, Int)] = {
    val ca: java.util.Calendar = java.util.Calendar.getInstance()
    ca.setTime(new java.util.Date(time))
    ca.set(java.util.Calendar.HOUR_OF_DAY, 0)
    ca.set(java.util.Calendar.MINUTE, 0)
    ca.set(java.util.Calendar.SECOND, 0)
    ca.set(java.util.Calendar.MILLISECOND, 0)
    val min = ca.getActualMinimum(java.util.Calendar.DAY_OF_MONTH)
    ca.set(java.util.Calendar.DAY_OF_MONTH, min)
    val st: Long = ca.getTime.getTime
    val max = ca.getActualMaximum(java.util.Calendar.DAY_OF_MONTH)
    ca.set(java.util.Calendar.DAY_OF_MONTH, max)
    Some(st, ca.getTime.getTime + Date.DAY_TIME - 1 - Date.DAY_TIME, max)
  }

  def apply(yyyyMMdd: String): Month = apply(Time(yyyyMMdd))
  def apply(time: Time): Month = apply(time.time)
  def apply(time: Long): Month = time match {
    case Month(st, et, len) => Month(st, et, len)
    case _ => null
  }
}